package com.controler.joystick;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.licheedev.modbus4android.ModbusCallback;
import com.licheedev.modbus4android.ModbusParam;
import com.licheedev.modbus4android.param.TcpParam;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.msg.WriteRegistersResponse;

public class MainActivity extends AppCompatActivity {

//    private RockerTouch touch;
    private RockerSpeed R_speed;
    private RokerAngle R_angle;

    private Button btn_connect;    // 建立连接
    private Button btn_start;      // 开启
    private Button btn_stop;       // 停止
    private EditText edit_ip;

    private boolean isConnect;
    private boolean isStart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        touch = (RockerTouch)findViewById(R.id.rocker);   //获取摇杆
        R_speed = (RockerSpeed)findViewById(R.id.rockerSpeed);
        R_angle = (RokerAngle)findViewById(R.id.rockerAngle);

        btn_connect = (Button)findViewById(R.id.btn_connect);
        btn_start = (Button)findViewById(R.id.btn_start);
        btn_stop = (Button)findViewById(R.id.btn_stop);
        edit_ip = (EditText)findViewById(R.id.text_ip);
        edit_ip.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                SharedPreferences sp = getSharedPreferences("IpData",MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("ip",s.toString());
                editor.commit();
            }
        });
        SharedPreferences sp = getSharedPreferences("IpData",MODE_PRIVATE);
        String ip = sp.getString("ip","192.168.1.10");
        edit_ip.setText(ip);

        btn_connect.setOnClickListener(onClickListener);
        btn_start.setOnClickListener(onClickListener);
        btn_stop.setOnClickListener(onClickListener);

        isConnect  = false;
        isStart = false;

    }

    Handler handler=new Handler();

    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            short[] data = new short[3];
            if(isStart == true){
                data[0] = 1;
            }else{
                data[0] = 0;
            }

//            data[1] = (short)(touch.getSpeed()*100);
//            data[2] = (short)(touch.getDeg()*100)
//
            data[1] = (short)(R_speed.getSpeed()*100);
            data[2] = (short)(R_angle.getAngle()*100);

            ModbusManager.get().writeRegisters(1, 0, data, new ModbusCallback<WriteRegistersResponse>() {
                @Override
                public void onSuccess(WriteRegistersResponse writeRegistersResponse) {

                }

                @Override
                public void onFailure(Throwable tr) {
                    Toast.makeText(MainActivity.this,"发送数据失败!",Toast.LENGTH_LONG);
                }

                @Override
                public void onFinally() {

                }
            });

            handler.postDelayed(this, 100);
        }
    };

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn_connect:
                    isStart = false;
                    if(isConnect== false)
                    {
                        /* 建立连接 */
                        String host = edit_ip.getText().toString().trim();
//                        int port = 0;
//                        try {
//                            port = Integer.parseInt(edit_ip.getText().toString().trim());
//                        } catch (NumberFormatException e) {
//                            //e.printStackTrace();
//                        }
                        ModbusParam param;
                        param = TcpParam.create(host, 9999)
                                .setTimeout(500)
                                .setRetries(2)
                                .setEncapsulated(false)
                                .setKeepAlive(true);
                        ModbusManager.get().closeModbusMaster();   //先关闭  然后开启
                        ModbusManager.get().init(param, new ModbusCallback<ModbusMaster>() {
                            @Override
                            public void onSuccess(ModbusMaster modbusMaster) {
                                Toast.makeText(MainActivity.this,"打开成功!",Toast.LENGTH_LONG);
                                btn_connect.setText("断开");
                                isConnect = true;
                            }

                            @Override
                            public void onFailure(Throwable tr) {
                                Toast.makeText(MainActivity.this,"打开失败!",Toast.LENGTH_LONG);
                            }

                            @Override
                            public void onFinally() {

                            }
                        });
                        handler.postDelayed(runnable, 100);//
                        Toast.makeText(getApplicationContext(),"打开成功!",Toast.LENGTH_LONG);
                    }else{
                        handler.removeCallbacks(runnable);
                        ModbusManager.get().closeModbusMaster();   //先关闭  然后开启
                        btn_connect.setText("连接");
                        isConnect = false;

                    }
                    break;
                case R.id.btn_start:
                    isStart = true;
                    break;
                case R.id.btn_stop:
                    isStart = false;
                    break;
            }
        }
    };

}